package Com.concurrent.practice.chapter1;
/**
 * 非线程安全的数据控制
 * @author hongxiao.z
 * @date   2014-3-28  上午11:53:22
 */
public class UnsafeSequence 
{
	private volatile int value;
	
	//value++ 会在低层执行 读取value值， 操作value计算， 保存value值三步操作
	//多线程操作可能会出现数据不同步的情况
	public int getNext(int num)
	{
		value = num;
		return value;
	}
	
	public static int id = 0;
	
	public synchronized static int getId()
	{
		return ++id;
	}
	
	public static void main(String[] args) 
	{
		UnsafeSequence sequence = new UnsafeSequence();
		ValueModify v1 = new ValueModify(sequence);
		v1.start();
		ValueModify v2 = new ValueModify(sequence);
		v2.start();
		ValueModify v3 = new ValueModify(sequence);
		v3.start();
		ValueModify v4 = new ValueModify(sequence);
		v4.start();
		ValueModify v5 = new ValueModify(sequence);
		v5.start();
		ValueModify v6 = new ValueModify(sequence);
		v6.start();
		
		
	}
}

class ValueModify extends Thread
{
	UnsafeSequence sequence;
	
	@Override
	public void run() {
		while(true)
		{
			System.out.println(this.getName() + " : " + sequence.getNext(UnsafeSequence.getId()));
			try
			{
				Thread.sleep(1000);
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}
	}
	
	ValueModify(UnsafeSequence sequence)
	{
		this.sequence = sequence;
	}
}
